package abc.database.interfaces;

import org.springframework.jdbc.core.JdbcTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public interface SqlServerHelper extends ISqlHelper<Map<String, Object>> {
    default List<Map<String, Object>> getTableList(String dbname, JdbcTemplate jdbcTemplate) {
        String sql = "select name as table_name, '' as table_comment, case when xtype='v' then 'view' else 'table' end as type from sysobjects where xtype='u' OR xtype='v'";
        return jdbcTemplate.queryForList(sql);
    }

    default List<Map<String, Object>> getColumnList(String dbname, JdbcTemplate jdbcTemplate) {
        List<Map<String, Object>> columns = new ArrayList<>();
        List<Map<String, Object>> tableList = this.getTableList(dbname, jdbcTemplate);
        if(tableList == null) {
            return columns;
        }
        tableList.forEach(a-> {
            if(!a.containsKey("table_name") || a.get("table_name")==null) {
                return;
            }
            String tablename = a.get("table_name").toString();
            String sql = String.format( "select '%s' as table, COLUMN_NAME AS annotationColumnName,'' column_comment as comment,DATA_TYPE AS dataType, (SELECT COLUMNPROPERTY( OBJECT_ID('%s'),column_name,'IsIdentity')) as isAutoIncrement, 0 as keyFlag, 0 as keyIdentityFlag, COLUMN_NAME as propertyName, COLUMN_NAME as [name], 1 as [convert], 0 as versionField from information_schema.COLUMNS where TABLE_NAME='%s'", tablename, tablename, tablename);
            List<Map<String, Object>> cols = jdbcTemplate.queryForList(sql);
            if(cols!=null && cols.size()>0) {
                columns.addAll(cols);
            }
        });

        return columns;
    }
}
